<template>
  <a-button
    type="primary"
    v-if="!user.isLogin"
    class="user-profile-component"
    @click="login"
  >
    登录
  </a-button>
  <div v-else>
    <a-dropdown-button class="user-profile-component">
      <router-link to="/setting">{{ user.data && user.data.nickName }}</router-link>
      <template v-slot:overlay>
        <a-menu class="user-profile-dropdown">
          <a-menu-item key="0" @click="logout">登出</a-menu-item>
        </a-menu>
      </template>
    </a-dropdown-button>
  </div>
</template>
<script lang="ts" setup>
import { Button as aButton } from "ant-design-vue";
import { computed, onMounted } from "vue";
import { GlobalDataProps } from "../store/index";
import { useStore } from "vuex";
import {
  DropdownButton as aDropdownButton,
  message,
  Menu as aMenu,
  MenuItem as aMenuItem,
} from "ant-design-vue";
import { useRouter } from "vue-router";
import { UserProps } from "@/store/user";
import axios from "axios";

const store = useStore<GlobalDataProps>();
const router = useRouter();
const user = computed<UserProps>(() => store.state.user);
console.log(user.value.isLogin);

const currentUser = computed(() => {
  return store.state.user;
});
onMounted(() => {
  console.log("user", user.value);
  if(!currentUser.value.isLogin && currentUser.value.token){
      //设置全局请求头
      console.log('userprofile token',currentUser.value.token);
      axios.defaults.headers.common.Authorization = `Bearer ${currentUser.value.token}`;
      store.dispatch("fetchCurrentUser")
        .catch(()=>{
          message.error('登录过期，请重新登录',2);
          localStorage.removeItem('token');
          delete axios.defaults.headers.common.Authorization;
        })
  }
});

const login = () => {
  // store.commit("login");
  router.push("/login");
  // message.success("登录成功");
};

const logout = () => {
  store.commit("logout");
  message.success("退出成功");
  setTimeout(() => {
    router.push("/");
  }, 2000);
};
</script>
<style scoped lang="css"></style>
